import { Button, Popover } from "antd";
import { FC, ReactElement, useEffect, useState } from "react";
import styled from "styled-components";
import { BackUser, queryUser, updateUserRole } from "../../../api/userApi";

interface IProps {}

const UserManage: FC<IProps> = (): ReactElement => {
  const [user, setUser] = useState<BackUser>({ count: 0, users: [] });

  useEffect(() => {
    queryUser({}).then(({ data }) => {
      console.log(data);
      if (data) setUser(data);
    });
  }, []);

  return (
    <Container>
      <THead>
        <span>用户名</span>
        <span>权限</span>
      </THead>
      {user.users.map(user => (
        <UserItem key={user._id} user={user} />
      ))}
    </Container>
  );
};

export default UserManage;

interface IUserItem {
  user: BackUser["users"][number];
}

const UserItem: FC<IUserItem> = ({ user: { _id, username, role } }) => {
  const [loading, setLoading] = useState(false);
  const [userRole, setUserRole] = useState(role);

  const changeRole = () => {
    setLoading(true);
    const target = userRole ? 0 : 1;
    updateUserRole({ _id, role: target }).then(({ data }) => {
      if (data && data.code === 0) setUserRole(target);
      setLoading(false);
    });
  };

  return (
    <Item>
      <span>{username}</span>
      <span>
        {role}
        <Popover
          title='确认操作'
          content={
            <Button loading={loading} onClick={changeRole}>
              确认
            </Button>
          }
        >
          <Button
            loading={loading}
            type={userRole ? "dashed" : "primary"}
            danger={!!userRole}
          >
            {userRole ? "降为游客" : "提升管理员"}
          </Button>
        </Popover>
      </span>
    </Item>
  );
};

const Item = styled.div`
  margin-top: 0.5rem;
  padding: 0.5rem;
  display: flex;
  background: #fff;
  border-radius: 0.2rem;
  box-shadow: 5px 5px 10px #d6d6d6, -5px -5px 10px #ffffff;
  transition: transform 0.3s linear, box-shadow 0.3s linear;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 5px 5px 10px #d6d6d6, -5px -5px 10px #eeeeee;
  }
  span {
    flex: 1;
    display: flex;
    align-items: center;
  }
  span:last-child {
    display: flex;
    justify-content: space-between;
  }
`;

const THead = styled(Item)`
  font-weight: bold;
  background: #000;
  color: #c7b98d;
  position: sticky;
  position: -webkit-sticky;
  top: 0.5rem;
  z-index: 1;
  padding: 1rem;
`;

const Container = styled.div`
  background: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
  padding: 1rem;
  padding-top: 0.5rem;
`;
